<template>
  <el-form :model="formModel" :rules="formRules" ref="formRef">
    <template v-for="field in formFields" :key="field.name">
      <component
        :is="getComponentType(field.type)"
        v-bind="getFieldProps(field)"
        v-model="formModel[field.name]"
      >
        <template v-if="field.type === 'select'">
          <el-option
            v-for="option in field.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </template>
        <template v-if="field.type === 'radio'">
          <el-radio
            v-for="option in field.options"
            :key="option.value"
            :label="option.value"
            >{{ option.label }}</el-radio
          >
        </template>
        <template v-if="field.type === 'checkbox'">
          <el-checkbox
            v-for="option in field.options"
            :key="option.value"
            :label="option.value"
            >{{ option.label }}</el-checkbox
          >
        </template>
      </component>
    </template>
    <el-button @click="handleSubmit">Submit</el-button>
  </el-form>
</template>

<script setup>
import { ref, reactive } from "vue";
import {
  ElForm,
  ElInput,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElCheckboxGroup,
  ElCheckbox,
  ElButton,
} from "element-plus";

const props = defineProps({
  formFields: {
    type: Array,
    required: true,
  },
});

const formModel = reactive({});
const formRules = reactive({});
const formRef = ref(null);

const getComponentType = (type) => {
  switch (type) {
    case "text":
      return "el-input";
    case "select":
      return "el-select";
    case "radio":
      return "el-radio-group";
    case "checkbox":
      return "el-checkbox-group";
    default:
      return "el-input";
  }
};

const getFieldProps = (field) => {
  const props = {
    placeholder: field.placeholder || "",
    ...field.extraProps,
  };
  if (["select", "radio", "checkbox"].includes(field.type)) {
    props.options = field.options || [];
  }
  return props;
};

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log("Submit!", formModel);
    } else {
      console.log("Validation failed.");
    }
  });
};

// Initialize formModel and formRules based on formFields
props.formFields.forEach((field) => {
  formModel[field.name] = field.defaultValue || "";
  if (field.required) {
    formRules[field.name] = [
      {
        required: true,
        message: `${field.label} is required`,
        trigger: "blur",
      },
    ];
  }
  if (field.regex) {
    formRules[field.name].push({
      pattern: field.regex,
      message: field.regexMessage || `${field.label} is invalid`,
      trigger: "blur",
    });
  }
});
</script>
